package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("本次请求路径为"+request.getRequestURI());
        Object employee = request.getSession().getAttribute("employee");
        Object loginUser = request.getSession().getAttribute("loginUser");
        if (employee!=null || loginUser!=null){
            //已登录，放行
            return true;
        }
        log.info("拦截到未登录用户");
        //响应json数据给前端，由前端跳转到登录页面
        String json = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(json);
        return false;

    }
}
